package com.cat.dynamicPlanning02;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/
 * @create 2025/10/17 21:17
 * @since JDK17
 */

public class Solution22 {
    int f(int[] prices) {
        int ans = 0, n = prices.length;
        for (int i = 1; i < n; i++) {
            ans += Math.max(0, prices[i] - prices[i - 1]);
        }
        return ans;
    }
    public int maxProfit(int k, int[] prices) {
        int n = prices.length, best = 0;
        if (k >= n / 2) {
            return f(prices);
        }
        int[][] dp = new int[k + 1][n];
        for (int i = 1; i <= k; i++) {
            best = dp[i - 1][0] - prices[0];
            for (int j = 1; j < n; j++) {
                dp[i][j] = Math.max(dp[i][j - 1], best + prices[j]);
                best = Math.max(best, dp[i - 1][j] - prices[j]);
            }
        }

        return dp[k][n - 1];
    }
}
